<template>
	<div class="card-fill layout-padding" v-loading="loading" element-loading-text="Loading...">
		<el-card shadow="hover" class="layout-padding-auto create-form">
			<el-form ref="formRef" :model="stateData.vmModel" :rules="formRules" label-width="120px">
				<div class="form-section">
					<div class="section-title">
						<i class="_wtmicon _wtmicon-wxbzhanghu"></i>
						<span>单据信息</span>
					</div>

					<el-row :gutter="20">
						<el-col :xs="24" :lg="12" class="mb20">
							<el-form-item ref="Entity_BillCode_FormItem" prop="Entity.BillCode">
								<template #label>
									<WtmLabelTooltip label="单据编号" tooltip="单据编号" />
								</template>
								<el-input v-model="stateData.vmModel.Entity.BillCode" clearable class="width100" disabled placeholder="自动生成"></el-input>
							</el-form-item>
						</el-col>
						<el-col :xs="24" :lg="12" class="mb20">
							<el-form-item ref="Entity_Remark_FormItem" prop="Entity.Remark">
								<template #label>
									<WtmLabelTooltip label="备注" tooltip="备注" />
								</template>
								<el-input v-model="stateData.vmModel.Entity.Remark" clearable class="width100"></el-input>
							</el-form-item>
						</el-col>
					</el-row>
				</div>

				<div class="form-section">
					<div class="section-title">
						<i class="_wtmicon _wtmicon-wxbzhanghu"></i>
						<span>申请人员信息</span>
					</div>

					<el-row :gutter="20">
						<el-col :xs="24" :lg="12" class="mb20">
							<el-form-item
								ref="Entity_PersonId_FormItem"
								prop="Entity.PersonId"
								:rules="[{ required: true, message: '申请人为必填项', trigger: 'blur' }]"
							>
								<template #label>
									<WtmLabelTooltip label="申请人" tooltip="申请人员工实体" />
								</template>
								<WtmPersonSelector v-model="stateData.vmModel.Entity.PersonId" :prefill-person="stateData.prefillPerson" @change="onPersonSelected" />
							</el-form-item>
						</el-col>
						<el-col :xs="24" :lg="12" class="mb20">
							<el-form-item ref="Entity_StaffNo_FormItem" prop="Entity.StaffNo">
								<template #label>
									<WtmLabelTooltip label="员工工号" tooltip="员工工号" />
								</template>
								<el-input v-model="stateData.vmModel.Entity.StaffNo" clearable class="width100" disabled placeholder="选取人员后带入"></el-input>
							</el-form-item>
						</el-col>
						<el-col :xs="24" :lg="12" class="mb20">
							<el-form-item ref="Entity_Name_FormItem" prop="Entity.Name">
								<template #label>
									<WtmLabelTooltip label="员工姓名" tooltip="员工姓名" />
								</template>
								<el-input v-model="stateData.vmModel.Entity.Name" clearable class="width100" disabled placeholder="选取人员后带入"></el-input>
							</el-form-item>
						</el-col>
					</el-row>
				</div>

				<div class="form-section">
					<div class="section-title">
						<i class="_wtmicon _wtmicon-wxbzhanghu"></i>
						<span>换班申请信息</span>
					</div>

					<el-row :gutter="20">
						<el-col :xs="24" :lg="12" class="mb20">
							<el-form-item
								ref="Entity_StartTime_FormItem"
								prop="Entity.StartTime"
								:rules="[{ required: true, message: '换班时间为必填项', trigger: 'blur' }]"
							>
								<template #label>
									<WtmLabelTooltip label="换班时间" tooltip="换班时间(通常为当天)" />
								</template>
								<el-date-picker
									v-model="stateData.vmModel.Entity.StartTime"
									type="date"
									:disabled-date="disabledDate"
									clearable
									class="width100"
									placeholder="请选择换班时间"
								></el-date-picker>
							</el-form-item>
						</el-col>
						<!-- <el-col :xs="24" :lg="12" class="mb20">
							<el-form-item
								ref="Entity_EndTime_FormItem"
								prop="Entity.EndTime"
								:rules="[{ required: true, message: '结束时间为必填项', trigger: 'blur' }]"
							>
								<template #label>
									<WtmLabelTooltip label="结束时间" tooltip="换班结束时间(通常为当天)" />
								</template>
								<el-date-picker
									v-model="stateData.vmModel.Entity.EndTime"
									type="date"
									:disabled-date="disabledDate"
									clearable
									class="width100"
									placeholder="请选择结束时间"
								></el-date-picker>
							</el-form-item>
						</el-col> -->
						<el-col :xs="24" :lg="12" class="mb20">
							<el-form-item
								ref="Entity_SwapPersonId_FormItem"
								prop="Entity.SwapPersonId"
								:rules="[{ required: true, message: '换班对方人员为必填项', trigger: 'blur' }]"
							>
								<template #label>
									<WtmLabelTooltip label="换班对方人员" tooltip="对方人员实体（限本部门，不能选择自己）" />
								</template>
								<WtmPersonSelector
									v-model="stateData.vmModel.Entity.SwapPersonId"
									:group-id="stateData.vmModel.Entity.GroupId"
									:exclude-person-ids="stateData.vmModel.Entity.PersonId"
									placeholder="请输入工号或姓名查询本部门人员（不能选择自己）"
									@change="onSwapPersonSelected"
								/>
							</el-form-item>
						</el-col>
						<el-col :xs="24" :lg="12" class="mb20">
							<el-form-item ref="Entity_SwapStaffNo_FormItem" prop="Entity.SwapStaffNo">
								<template #label>
									<WtmLabelTooltip label="换班对方工号" tooltip="换班对方工号" />
								</template>
								<el-input
									v-model="stateData.vmModel.Entity.SwapStaffNo"
									clearable
									class="width100"
									disabled
									placeholder="选取换班人员后带入"
								></el-input>
							</el-form-item>
						</el-col>
						<el-col :xs="24" :lg="12" class="mb20">
							<el-form-item ref="Entity_SwapName_FormItem" prop="Entity.SwapName">
								<template #label>
									<WtmLabelTooltip label="换班对方姓名" tooltip="换班对方姓名" />
								</template>
								<el-input v-model="stateData.vmModel.Entity.SwapName" clearable class="width100" disabled placeholder="选取换班人员后带入"></el-input>
							</el-form-item>
						</el-col>

						<!-- 换班对方排班记录选择 -->
						<el-col v-if="stateData.vmModel.Entity.SwapPersonId" :xs="24" :lg="12" class="mb20">
							<el-form-item
								label="换班对方排班记录"
								prop="Entity.SwapShiftId"
								:rules="[{ required: true, message: '换班对方排班记录为必填项', trigger: 'blur' }]"
							>
								<template #label>
									<WtmLabelTooltip label="换班对方排班记录" tooltip="选择换班对方的排班记录" />
								</template>
								<el-select
									v-model="stateData.vmModel.Entity.SwapShiftId"
									placeholder="请选择排班记录"
									class="width100"
									:loading="swapPersonShiftLoading"
									:disabled="swapPersonShiftOptions.length === 0 && !swapPersonShiftLoading"
									clearable
								>
									<el-option v-for="option in swapPersonShiftOptions" :key="option.value" :label="option.label" :value="option.value" />
									<el-option
										v-if="swapPersonShiftOptions.length === 0 && !swapPersonShiftLoading"
										value=""
										label="该人员暂无可用的排班记录"
										disabled
									/>
								</el-select>
							</el-form-item>
						</el-col>

						<el-col :xs="24" :lg="12" class="mb20">
							<el-form-item ref="Entity_Reason_FormItem" prop="Entity.Reason" :rules="[{ required: true, message: '事由为必填项', trigger: 'blur' }]">
								<template #label>
									<WtmLabelTooltip label="事由" tooltip="换班事由" />
								</template>
								<el-input
									v-model="stateData.vmModel.Entity.Reason"
									type="textarea"
									:rows="2"
									clearable
									class="width100"
									placeholder="请输入换班事由"
								></el-input>
							</el-form-item>
						</el-col>
					</el-row>
				</div>

				<div class="form-section">
					<div class="section-title">
						<i class="_wtmicon _wtmicon-wxbzhanghu"></i>
						<span>工作信息</span>
					</div>
					<el-row :gutter="20">
						<el-col :xs="24" :lg="12" class="mb20">
							<WtmOrgSelector
								v-model="stateData.vmModel.Entity.OrgId"
								label="公司"
								prop="Entity.OrgId"
								:auth="false"
								:disabled="true"
								placeholder="选取人员后带入"
							/>
						</el-col>
						<el-col :xs="24" :lg="12" class="mb20">
							<WtmDeptSelector v-model="stateData.vmModel.Entity.GroupId" prop="Entity.GroupId" label="所属部门" :auth="false" :disabled="true" />
						</el-col>
					</el-row>
				</div>
			</el-form>
		</el-card>
	</div>
</template>

<script setup lang="ts" name="message._system.common.vm.add;false">
import ElMessage from 'element-plus/es/components/message/index';
import { reactive, ref, getCurrentInstance, onMounted, computed, nextTick, type ComponentInternalInstance } from 'vue';
import { SysDailyShiftSwapRequestBillApi as api } from '/@/views/daily/sysdailyshiftswaprequestbill/api';
import other from '/@/utils/other';
import { ISysDailyShiftSwapRequestBillVm } from '/@/views/daily/sysdailyshiftswaprequestbill/api/interface';
import { IViewModel } from '/@/types/common';
import { SysAttendanceRecordApi as attendanceApi } from '/@/views/hr/sysattendancerecord/api';
import type { ISearchByPersonRequest } from '/@/views/hr/sysattendancerecord/api/interface';
import { formatDate } from '/@/utils/formatTime';
import { commonApi } from '/@/api/common';

// 常量定义
const BILL_STATUS = {
	DRAFT: '草稿',
	FORMAL: '正文',
} as const;

const WORKFLOW_STATUS = {
	PENDING: '待提交',
	SUBMITTING: '提交中',
} as const;

const BUTTON_TEXTS = {
	SAVE: '保存',
	SUBMIT: '提交',
	CLOSE: '关闭',
} as const;

const ci = getCurrentInstance() as ComponentInternalInstance;
const loading = ref(false);
const formRef = ref();
const hasSavedOnce = ref(false);

// 动态表单验证规则
const formRules = computed(() => {
	const rules: Record<string, any[]> = {
		'Entity.StartTime': [{ required: true, message: '请选择开始时间', trigger: 'change' }],
		'Entity.EndTime': [{ required: true, message: '请选择结束时间', trigger: 'change' }],
	};

	return rules;
});

const stateData = reactive<IViewModel<ISysDailyShiftSwapRequestBillVm>>({
	vmModel: {
		Entity: {
			ID: null,
			PersonId: null,
			OrgId: null,
			StaffNo: null,
			Name: null,
			StartTime: null,
			EndTime: null,
			Reason: null,
			SwapPersonId: null,
			SwapStaffNo: null,
			SwapName: null,
			Approver: null,
			ApprovalTime: null,
			GroupId: null,
			BillCode: null,
			BillStatus: null,
			WorkflowStatus: null,
			Remark: null,
			SwapShiftId: null,
		} as any, // 使用类型断言来支持额外字段
		ActionName: null,
		IsMyApprove: null,
	},

	AllSysGroups: [] as any[],
	prefillPerson: null as any, // 预填充的申请人信息
});

// 排班记录相关状态
const swapPersonShiftLoading = ref(false); // 换班对方排班记录加载状态
const swapPersonShiftOptions = ref<Array<{ value: string; label: string }>>([]); // 换班对方排班记录选项

// 日期限制：前后60天
const disabledDate = computed(() => {
	return (time: Date) => {
		const today = new Date();
		const sixtyDaysAgo = new Date(today.getTime() - 60 * 24 * 60 * 60 * 1000);
		const sixtyDaysLater = new Date(today.getTime() + 60 * 24 * 60 * 60 * 1000);
		return time < sixtyDaysAgo || time > sixtyDaysLater;
	};
});

// 计算属性
const hasEntityId = computed(() => {
	const entity = stateData.vmModel.Entity as any;
	return !!(entity && entity.ID);
});

const canSubmit = computed(() => hasEntityId.value && hasSavedOnce.value);

// 统一的成功处理函数
const handleSuccess = (response: any, isSubmit = false) => {
	// 根据操作类型显示不同的消息
	if (isSubmit) {
		ElMessage.success(ci.proxy?.$t('message._system.common.vm.submittip') || '提交成功');
		emit('refresh');
		closeDialog();
	} else {
		ElMessage.success(ci.proxy?.$t('message._system.common.vm.savetip') || '保存成功');
		emit('refresh');
		// 保存后不关闭弹窗，更新实体ID
		if (response?.Entity?.ID) {
			stateData.vmModel.Entity = response.Entity;
		} else if (response?.ID) {
			(stateData.vmModel.Entity as any).ID = response.ID;
		}
		hasSavedOnce.value = true;
	}

	loading.value = false;
	nextTick(() => {
		setupHeaderButtons();
	});
};

// 统一的错误处理函数
const handleError = (error: any) => {
	other.setFormError(ci, error);
	loading.value = false;
};

// 公共的API请求处理函数
const handleApiRequest = (apiCall: () => Promise<any>, beforeSubmit: () => void, isSubmit = false) => {
	other.validateFormWithMessage(formRef.value, () => {
		loading.value = true;
		beforeSubmit();
		apiCall()
			.then((response: any) => handleSuccess(response, isSubmit))
			.catch(handleError);
	});
};

// 人员选择变化处理
const onPersonSelected = (value: any, person: any) => {
	if (person) {
		// 自动填充员工信息
		stateData.vmModel.Entity.StaffNo = person.StaffNo || '';
		stateData.vmModel.Entity.Name = person.Name || '';
		stateData.vmModel.Entity.OrgId = person.OrgId || '';
		stateData.vmModel.Entity.GroupId = person.GroupId || '';
	} else {
		// 清空员工信息
		stateData.vmModel.Entity.StaffNo = null;
		stateData.vmModel.Entity.Name = null;
		stateData.vmModel.Entity.OrgId = null;
		stateData.vmModel.Entity.GroupId = null;
	}

	// 清空换班对方人员信息（因为部门可能已改变，或者需要重新选择）
	stateData.vmModel.Entity.SwapPersonId = null;
	stateData.vmModel.Entity.SwapStaffNo = null;
	stateData.vmModel.Entity.SwapName = null;
};

// 换班人员选择变化处理
const onSwapPersonSelected = async (value: any, person: any) => {
	if (person) {
		// 自动填充换班人员信息
		stateData.vmModel.Entity.SwapStaffNo = person.StaffNo || '';
		stateData.vmModel.Entity.SwapName = person.Name || '';

		// 加载该人员的排班记录
		await loadSwapPersonScheduleRecords(value);
	} else {
		// 清空换班人员信息
		stateData.vmModel.Entity.SwapStaffNo = null;
		stateData.vmModel.Entity.SwapName = null;

		// 清空排班记录
		swapPersonShiftOptions.value = [];
		stateData.vmModel.Entity.SwapShiftId = null;
	}
};

// 查询换班对方排班记录
const loadSwapPersonScheduleRecords = async (personId: string) => {
	try {
		swapPersonShiftLoading.value = true;
		// 清空之前选取的排班记录
		stateData.vmModel.Entity.SwapShiftId = null;
		swapPersonShiftOptions.value = [];

		// 构建查询参数 - 查询未来30天的排班记录
		const params: ISearchByPersonRequest = {
			PersonId: personId,
			Page: 1,
			Limit: 50,
			IsPlainText: true,
			IsEmunToString: true,
			ShiftDate: [formatDate(new Date(), 'yyyy-MM-dd'), formatDate(new Date(new Date().getTime() + 30 * 24 * 60 * 60 * 1000), 'yyyy-MM-dd')],
		};

		const response = await attendanceApi().getSchedulingByPerson(params);

		if (response.Data && Array.isArray(response.Data) && response.Data.length > 0) {
			const firstData = (response.Data as any[])[0];
			if (firstData && firstData.Records && Array.isArray(firstData.Records)) {
				const filteredData = firstData.Records.filter((record: any) => {
					return record.ID && record.ShiftDate && record.AttendanceShiftGroupName;
				});

				swapPersonShiftOptions.value = filteredData.map((record: any) => {
					const shiftName = record.AttendanceShift?.Name || record.AttendanceShiftGroupName || record.ShiftName || record.ShiftInfo || '未知班次';
					return {
						value: record.ID,
						label: `${record.ShiftDate} - ${shiftName}`,
					};
				});
			}
		}

		if (swapPersonShiftOptions.value.length === 0) {
			ElMessage.info('该人员暂无可用的排班记录');
		}
	} catch (error) {
		console.error('查询换班对方排班记录失败:', error);
		ElMessage.error('查询换班对方排班记录失败');
		swapPersonShiftOptions.value = [];
	} finally {
		swapPersonShiftLoading.value = false;
	}
};

// 取消
const onClose = () => {
	closeDialog();
};

// 保存
const onSave = () => {
	handleApiRequest(
		() => {
			// 创建一个深拷贝，确保新增时不发送无效的 ID 字段
			const submitData = JSON.parse(JSON.stringify(stateData.vmModel));
			if (!submitData.Entity.ID) {
				// 如果没有有效的 ID，删除该字段
				delete submitData.Entity.ID;
			}
			return api().add(submitData);
		},
		() => {
			stateData.vmModel.Entity.BillStatus = BILL_STATUS.DRAFT;
		},
		false // 保存后不关闭弹窗
	);
};

// 提交
const onSubmit = () => {
	handleApiRequest(
		() => api().edit(stateData.vmModel),
		() => {
			stateData.vmModel.Entity.WorkflowStatus = WORKFLOW_STATUS.SUBMITTING;
		},
		true // 提交后关闭弹窗
	);
};

// 初始化页面数据
const initializePageData = () => {
	const wtmdata = ci.attrs['wtmdata'] as any;
	if (wtmdata?.ID) {
		(stateData.vmModel.Entity as any).ID = wtmdata.ID;
		hasSavedOnce.value = true;
	}
};

// 获取当前登录人信息，默认带出申请人信息
const getCurrentPersonInfo = async () => {
	try {
		const response = await commonApi().getPersonInfo({});
		if (response && response.Data) {
			const personInfo = response.Data;
			// 设置预填充信息（用于WtmPersonSelector显示）
			stateData.prefillPerson = personInfo;
			// 设置PersonId，这样表单会有默认值
			stateData.vmModel.Entity.PersonId = personInfo.ID;
			// 填充其他相关信息
			stateData.vmModel.Entity.StaffNo = personInfo.StaffNo || '';
			stateData.vmModel.Entity.Name = personInfo.Name || '';
			stateData.vmModel.Entity.OrgId = personInfo.OrgId || '';
			stateData.vmModel.Entity.GroupId = personInfo.GroupId || '';
		}
	} catch (error) {
		console.warn('获取当前登录人信息失败:', error);
		// 失败时不影响正常使用，用户可以手动选择
	}
};

// 加载页面数据
const loadPageData = async () => {
	const API_ENDPOINTS = {
		GROUPS: '/api/SysDailyShiftSwapRequestBill/GetSysGroups',
	} as const;

	const [groups, billCode] = await Promise.allSettled([
		other.getSelectList(API_ENDPOINTS.GROUPS, [], false),
		api().getBillCode(),
		getCurrentPersonInfo(), // 获取当前用户信息，默认带入
	]);

	// 处理成功的结果
	if (groups.status === 'fulfilled') stateData.AllSysGroups = groups.value;
	if (billCode.status === 'fulfilled') stateData.vmModel.Entity.BillCode = billCode.value.Data as string;
};

// 页面加载时
onMounted(async () => {
	loading.value = true;
	initializePageData();

	try {
		await loadPageData();
	} catch (error) {
		other.setFormError(ci, error);
	} finally {
		loading.value = false;
		nextTick(() => {
			setupHeaderButtons();
		});
	}
});

// 定义子组件向父组件传值事件
const emit = defineEmits(['refresh', 'closeDialog', 'updateHeaderButtons']);

// 关闭弹窗
const closeDialog = () => {
	emit('closeDialog');
};

// 设置对话框头部按钮
const setupHeaderButtons = () => {
	const headerButtons = [
		{
			text: BUTTON_TEXTS.SAVE,
			type: undefined,
			onClick: onSave,
			visible: !hasSavedOnce.value,
		},
		{
			text: BUTTON_TEXTS.SUBMIT,
			confirm: '提交单据以后无法修改，是否确认提交?',
			type: 'primary',
			onClick: onSubmit,
			visible: canSubmit.value,
		},
		{
			text: BUTTON_TEXTS.CLOSE,
			type: 'default',
			onClick: onClose,
			visible: true,
		},
	];

	emit('updateHeaderButtons', headerButtons);
};
</script>
